package com.tzkyzj.tiremanager.contorller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.tzkyzj.tiremanager.dto.ApiResponse;
import com.tzkyzj.tiremanager.dto.CostStatisticsResponse;
import com.tzkyzj.tiremanager.dto.TireBatchDto;
import com.tzkyzj.tiremanager.dto.TireVisualizationDTO;
import com.tzkyzj.tiremanager.entity.Tire;
import com.tzkyzj.tiremanager.entity.TirePhoto;
import com.tzkyzj.tiremanager.entity.User;
import com.tzkyzj.tiremanager.repository.TirePhotoRepository;
import com.tzkyzj.tiremanager.service.AuthService;
import com.tzkyzj.tiremanager.service.TirePhotoService;
import com.tzkyzj.tiremanager.service.TireService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/tires")
public class TireController {

    private static final Logger log = LoggerFactory.getLogger(TireService.class);

    @Autowired
    private TireService tireService;

    @Autowired
    private TirePhotoRepository tirePhotoRepository;

    @Autowired
    private TirePhotoService tirePhotoService;

    @Autowired
    private AuthService authService;

    // 获取当前用户并检查权限的辅助方法
    private User getCurrentUser(HttpServletRequest request) {
        return (User) request.getAttribute("currentUser");
    }

    // 检查用户是否有权限访问轮胎数据的辅助方法
    private boolean hasAccessToTire(User user, Tire tire) {
        if (user == null || tire == null) return false;

        switch (user.getRole()) {
            case ADMIN:
                return true;
            case COMPANY:
                return user.getTransportCompany() != null &&
                        user.getTransportCompany().equals(tire.getTransportCompany());
            case DRIVER:
                return (user.getVehiclePlateNumber() != null &&
                        user.getVehiclePlateNumber().equals(tire.getVehiclePlateNumber())) ||
                        (user.getVehiclePlateNumber() != null &&
                                user.getVehiclePlateNumber().equals(tire.getTrailerPlateNumber()));
            default:
                return false;
        }
    }

    // 检查用户是否有权限访问运输公司的辅助方法
    private boolean hasAccessToCompany(User user, String company) {
        if (user == null || company == null) return false;

        switch (user.getRole()) {
            case ADMIN:
                return true;
            case COMPANY:
                return user.getTransportCompany() != null &&
                        user.getTransportCompany().equals(company);
            case DRIVER:
                // 司机只能访问自己所属运输公司的数据
                return user.getTransportCompany() != null &&
                        user.getTransportCompany().equals(company);
            default:
                return false;
        }
    }

    /**
     * 获取所有运输公司（JSON API - 用于Android客户端）
     */
    @GetMapping("/transport-companies")
    public List<String> getTransportCompaniesApi(HttpServletRequest request) {
        try {
            User currentUser = getCurrentUser(request);
            List<String> companies;

            if (currentUser.getRole() == User.UserRole.ADMIN) {
                companies = tireService.getAllTransportCompanies();
            } else if (currentUser.getRole() == User.UserRole.COMPANY || currentUser.getRole() == User.UserRole.DRIVER) {
                // COMPANY和DRIVER角色只显示自己注册时的公司
                if (currentUser.getTransportCompany() != null) {
                    companies = Collections.singletonList(currentUser.getTransportCompany());
                } else {
                    companies = new ArrayList<>();
                }
            } else {
                companies = new ArrayList<>();
            }

            log.info("获取运输公司列表成功，数量: {}", companies.size());
            return companies;
        } catch (Exception e) {
            log.error("获取运输公司列表失败", e);
            return new ArrayList<>();
        }
    }

    /**
     * 获取轮胎状态选项（JSON API - 用于Android客户端）
     */
    @GetMapping("/status-options")
    public List<String> getStatusOptionsApi() {
        try {
            List<String> statusOptions = Arrays.asList("使用中", "已报废");
            log.info("获取状态选项成功");
            return statusOptions;
        } catch (Exception e) {
            log.error("获取状态选项失败", e);
            return Arrays.asList("使用中", "已报废");
        }
    }

    /**
     * 获取费用统计数据
     */
    @GetMapping("/cost-statistics/data")
    public ResponseEntity<?> getCostStatisticsData(
            @RequestParam(required = false) String company,
            @RequestParam(required = false) Integer year,
            @RequestParam(required = false) Integer month,
            @RequestParam(required = false) String statType,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            HttpServletRequest request) {

        try {
            User currentUser = getCurrentUser(request);

            if (company != null && !hasAccessToCompany(currentUser, company)) {
                return ResponseEntity.status(HttpStatus.FORBIDDEN)
                        .body(Collections.singletonMap("error", "无权访问该运输公司的数据"));
            }

            // 对于COMPANY和DRIVER角色，强制使用用户注册时的公司
            if (currentUser.getRole() == User.UserRole.COMPANY || currentUser.getRole() == User.UserRole.DRIVER) {
                company = currentUser.getTransportCompany();
            }

            CostStatisticsResponse result = tireService.getCostStatistics(
                    company, year, month, statType, page, size);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Collections.singletonMap("error", "加载统计数据失败: " + e.getMessage()));
        }
    }

    /**
     * 导出费用统计报表
     */
    @GetMapping("/cost-statistics/export")
    public void exportCostStatistics(
            @RequestParam(required = false) String company,
            @RequestParam(required = false) Integer year,
            @RequestParam(required = false) Integer month,
            @RequestParam(required = false) String statType,
            HttpServletResponse response,
            HttpServletRequest request) {

        try {
            User currentUser = getCurrentUser(request);

            if (company != null && !hasAccessToCompany(currentUser, company)) {
                response.setStatus(HttpStatus.FORBIDDEN.value());
                response.getWriter().write("无权访问该运输公司的数据");
                return;
            }

            // 对于COMPANY和DRIVER角色，强制使用用户注册时的公司
            if (currentUser.getRole() == User.UserRole.COMPANY || currentUser.getRole() == User.UserRole.DRIVER) {
                company = currentUser.getTransportCompany();
            }

            tireService.exportCostStatistics(company, year, month, statType, response);
        } catch (Exception e) {
            log.error("导出费用统计报表失败", e);
            try {
                response.setContentType("text/plain;charset=UTF-8");
                response.getWriter().write("导出失败: " + e.getMessage());
            } catch (IOException ioException) {
                log.error("写入错误响应失败", ioException);
            }
        }
    }

    /**
     * 处理轮胎信息修改提交
     */
    @PostMapping("/{id}/edit")
    public ResponseEntity<Map<String, Object>> updateTire(@PathVariable("id") Long id,
                                                          @RequestParam String tireNumber,
                                                          @RequestParam(required = false) String tireBrand,
                                                          @RequestParam(required = false) String tireModel,
                                                          @RequestParam(required = false) String vehiclePlateNumber,
                                                          @RequestParam(required = false) String trailerPlateNumber,
                                                          @RequestParam(required = false) String transportCompany,
                                                          @RequestParam(required = false) BigDecimal tirePrice,
                                                          @RequestParam(required = false) BigDecimal installCost,
                                                          @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate installDate,
                                                          @RequestParam(required = false) Integer installMileage,
                                                          HttpServletRequest request) {

        Map<String, Object> response = new HashMap<>();
        try {
            User currentUser = getCurrentUser(request);
            Tire existingTire = tireService.findById(id)
                    .orElseThrow(() -> new IllegalArgumentException("无效的轮胎ID: " + id));

            if (!hasAccessToTire(currentUser, existingTire)) {
                response.put("success", false);
                response.put("message", "无权修改此轮胎信息");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(response);
            }

            if (tireNumber == null || tireNumber.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "轮胎号不能为空");
                return ResponseEntity.badRequest().body(response);
            }

            Optional<Tire> duplicateTire = tireService.findByTireNumber(tireNumber.trim());
            if (duplicateTire.isPresent() && !duplicateTire.get().getId().equals(id)) {
                response.put("success", false);
                response.put("message", "轮胎号已存在");
                return ResponseEntity.badRequest().body(response);
            }

            Tire tire = new Tire();
            tire.setId(id);
            tire.setTireNumber(tireNumber.trim());
            tire.setTireBrand(tireBrand);
            tire.setTireModel(tireModel);
            tire.setVehiclePlateNumber(vehiclePlateNumber);
            tire.setTrailerPlateNumber(trailerPlateNumber);

            // 只有ADMIN角色可以修改运输公司，COMPANY和DRIVER角色使用原有的运输公司
            if (currentUser.getRole() == User.UserRole.ADMIN) {
                tire.setTransportCompany(transportCompany);
            } else {
                tire.setTransportCompany(existingTire.getTransportCompany());
            }

            tire.setTirePrice(tirePrice);
            tire.setInstallCost(installCost);
            tire.setInstallDate(installDate);
            tire.setInstallMileage(installMileage);

            tireService.updateTireBasicInfo(tire);

            response.put("success", true);
            response.put("message", "轮胎信息修改成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "修改轮胎信息失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 获取轮胎列表数据
     */
    @GetMapping("/list")
    public Map<String, Object> listTires(HttpServletRequest request) {
        User currentUser = getCurrentUser(request);
        List<Tire> tires;

        switch (currentUser.getRole()) {
            case DRIVER:
                tires = tireService.getTiresByVehicle(currentUser.getVehiclePlateNumber());
                break;
            case COMPANY:
                tires = tireService.getTiresByTransportCompany(currentUser.getTransportCompany());
                break;
            case ADMIN:
                tires = tireService.getAllTires();
                break;
            default:
                tires = new ArrayList<>();
        }

        Map<String, Object> result = new HashMap<>();
        result.put("tires", tires);

        // 根据用户角色返回相应的运输公司列表
        List<String> transportCompanies;
        if (currentUser.getRole() == User.UserRole.ADMIN) {
            transportCompanies = tireService.getAllTransportCompanies();
        } else if (currentUser.getRole() == User.UserRole.COMPANY || currentUser.getRole() == User.UserRole.DRIVER) {
            if (currentUser.getTransportCompany() != null) {
                transportCompanies = Collections.singletonList(currentUser.getTransportCompany());
            } else {
                transportCompanies = new ArrayList<>();
            }
        } else {
            transportCompanies = new ArrayList<>();
        }
        result.put("transportCompanies", transportCompanies);

        // 根据用户角色返回相应的车辆信息
        List<String> plateNumbers = new ArrayList<>();
        if (currentUser.getRole() == User.UserRole.ADMIN) {
            // 从所有轮胎中提取不重复的车牌号
            plateNumbers = tires.stream()
                    .flatMap(tire -> {
                        List<String> plates = new ArrayList<>();
                        if (tire.getVehiclePlateNumber() != null && !tire.getVehiclePlateNumber().isEmpty()) {
                            plates.add(tire.getVehiclePlateNumber());
                        }
                        if (tire.getTrailerPlateNumber() != null && !tire.getTrailerPlateNumber().isEmpty()) {
                            plates.add(tire.getTrailerPlateNumber());
                        }
                        return plates.stream();
                    })
                    .distinct()
                    .collect(Collectors.toList());
        } else if (currentUser.getRole() == User.UserRole.COMPANY) {
            // 从公司轮胎中提取不重复的车牌号
            plateNumbers = tires.stream()
                    .flatMap(tire -> {
                        List<String> plates = new ArrayList<>();
                        if (tire.getVehiclePlateNumber() != null && !tire.getVehiclePlateNumber().isEmpty()) {
                            plates.add(tire.getVehiclePlateNumber());
                        }
                        if (tire.getTrailerPlateNumber() != null && !tire.getTrailerPlateNumber().isEmpty()) {
                            plates.add(tire.getTrailerPlateNumber());
                        }
                        return plates.stream();
                    })
                    .distinct()
                    .collect(Collectors.toList());
        } else if (currentUser.getRole() == User.UserRole.DRIVER) {
            if (currentUser.getVehiclePlateNumber() != null) {
                plateNumbers = Collections.singletonList(currentUser.getVehiclePlateNumber());
            } else {
                plateNumbers = new ArrayList<>();
            }
        }
        result.put("plateNumbers", plateNumbers);

        result.put("positions", tireService.getAllPositions());

        return result;
    }

    /**
     * 批量添加轮胎（支持索引照片格式）
     */
    @PostMapping(value = "/batch-add", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<Map<String, Object>> addTireBatch(
            @RequestParam String vehiclePlateNumber,
            @RequestParam(required = false) String trailerPlateNumber,
            @RequestParam String transportCompany,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate installDate,
            @RequestParam(required = false) Integer installMileage,
            @RequestParam("tireData") String tireDataJson,
            HttpServletRequest request) {  // 移除 @RequestParam MultipartFile[] allPhotos

        Map<String, Object> response = new HashMap<>();
        User currentUser = getCurrentUser(request);

        try {
            log.info("=== 开始批量添加轮胎（支持索引照片格式） ===");
            log.info("用户: {}", currentUser.getUsername());
            log.info("接收到的轮胎数据JSON长度: {}", tireDataJson.length());

            // 解析JSON数据
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.registerModule(new JavaTimeModule());
            objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

            List<TireBatchDto.TireInfo> tireInfos = objectMapper.readValue(
                    tireDataJson,
                    objectMapper.getTypeFactory().constructCollectionType(List.class, TireBatchDto.TireInfo.class)
            );

            log.info("解析出的轮胎数量: {}", tireInfos.size());

            // 从请求中提取所有照片文件（支持索引格式）
            Map<Integer, List<MultipartFile>> indexedPhotos = extractIndexedPhotos(request);
            log.info("提取到的索引照片数量: {} 组", indexedPhotos.size());

            // 使用索引分配照片
            assignPhotosToTiresByIndex(tireInfos, indexedPhotos);

            // 创建TireBatchDto
            TireBatchDto tireBatch = new TireBatchDto();
            tireBatch.setVehiclePlateNumber(vehiclePlateNumber);
            tireBatch.setTrailerPlateNumber(trailerPlateNumber);
            tireBatch.setTransportCompany(transportCompany);
            tireBatch.setInstallDate(installDate);
            tireBatch.setInstallMileage(installMileage);
            tireBatch.setTires(tireInfos);

            // 对于COMPANY和DRIVER角色，强制使用用户注册时的公司
            if (currentUser.getRole() != User.UserRole.ADMIN) {
                tireBatch.setTransportCompany(currentUser.getTransportCompany());

                // 对于DRIVER角色，还要强制使用用户注册时的车辆
                if (currentUser.getRole() == User.UserRole.DRIVER) {
                    tireBatch.setVehiclePlateNumber(currentUser.getVehiclePlateNumber());
                }
            }

            log.info("开始调用 tireService.saveTireBatch...");
            boolean success = tireService.saveTireBatch(tireBatch);

            if (success) {
                response.put("status", "success");
                response.put("message", "批量添加轮胎成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("status", "error");
                response.put("message", "没有成功保存任何轮胎记录");
                return ResponseEntity.badRequest().body(response);
            }
        } catch (Exception e) {
            log.error("添加轮胎失败", e);
            response.put("status", "error");
            response.put("message", "添加轮胎失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }


    /**
     * 从请求中提取带索引的照片（支持嵌套索引格式）
     */
    private Map<Integer, List<MultipartFile>> extractIndexedPhotos(HttpServletRequest request) {
        Map<Integer, List<MultipartFile>> indexedPhotos = new HashMap<>();

        try {
            if (request instanceof MultipartHttpServletRequest) {
                MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

                // 获取所有文件部分
                Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
                log.info("找到 {} 个文件字段", fileMap.size());

                for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
                    String paramName = entry.getKey();
                    MultipartFile file = entry.getValue();

                    // 解析带索引的照片字段名，支持两种格式：
                    // 1. photos[0] - 简单索引
                    // 2. photos[0][0] - 嵌套索引（轮胎索引和照片索引）
                    if (paramName.startsWith("photos[")) {
                        try {
                            int tireIndex = extractTireIndexFromParamName(paramName);

                            if (tireIndex >= 0) {
                                // 添加到对应的索引组
                                indexedPhotos.computeIfAbsent(tireIndex, k -> new ArrayList<>()).add(file);

                                log.info("提取照片: 字段名={}, 轮胎索引={}, 文件名={}, 大小={} bytes",
                                        paramName, tireIndex, file.getOriginalFilename(), file.getSize());
                            }
                        } catch (NumberFormatException e) {
                            log.warn("无法解析照片字段名的索引: {}", paramName);
                        }
                    }
                }
            } else {
                log.warn("请求不是 MultipartHttpServletRequest");
            }
        } catch (Exception e) {
            log.error("提取索引照片时发生错误", e);
        }

        return indexedPhotos;
    }

    /**
     * 从参数名中提取轮胎索引
     * 支持格式: photos[0] 和 photos[0][0]
     */
    private int extractTireIndexFromParamName(String paramName) {
        try {
            // 去掉 "photos[" 前缀
            String indexPart = paramName.substring(7);

            // 找到第一个闭合括号
            int endBracket = indexPart.indexOf(']');
            if (endBracket > 0) {
                String indexStr = indexPart.substring(0, endBracket);
                return Integer.parseInt(indexStr);
            }
        } catch (Exception e) {
            log.warn("解析参数名 {} 失败: {}", paramName, e.getMessage());
        }
        return -1;
    }

    /**
     * 按索引分配照片给轮胎（修复版）
     */
    private void assignPhotosToTiresByIndex(List<TireBatchDto.TireInfo> tireInfos,
                                            Map<Integer, List<MultipartFile>> indexedPhotos) {
        log.info("=== 开始按索引分配照片 ===");
        log.info("轮胎数量: {}, 索引照片组数: {}", tireInfos.size(), indexedPhotos.size());

        if (indexedPhotos.isEmpty()) {
            log.info("没有索引照片需要分配");
            for (TireBatchDto.TireInfo tireInfo : tireInfos) {
                tireInfo.setPhotos(new MultipartFile[0]);
            }
            return;
        }

        int totalAssigned = 0;

        // 按索引分配照片
        for (int i = 0; i < tireInfos.size(); i++) {
            TireBatchDto.TireInfo tireInfo = tireInfos.get(i);
            List<MultipartFile> photosForTire = indexedPhotos.get(i);

            if (photosForTire != null && !photosForTire.isEmpty()) {
                MultipartFile[] tirePhotosArray = photosForTire.toArray(new MultipartFile[0]);
                tireInfo.setPhotos(tirePhotosArray);
                totalAssigned += tirePhotosArray.length;

                log.info("✅ 轮胎[{}] {} 分配到 {} 张照片",
                        i, tireInfo.getTireNumber(), tirePhotosArray.length);

                // 详细记录每张照片
                for (int j = 0; j < tirePhotosArray.length; j++) {
                    MultipartFile photo = tirePhotosArray[j];
                    log.info("  照片[{}]: {}, 大小: {} bytes",
                            j, photo.getOriginalFilename(), photo.getSize());
                }
            } else {
                tireInfo.setPhotos(new MultipartFile[0]);
                log.info("❌ 轮胎[{}] {} 没有分配到照片", i, tireInfo.getTireNumber());
            }
        }

        log.info("=== 索引照片分配完成 ===");
        log.info("总共分配了 {} 张照片给 {} 个轮胎", totalAssigned, tireInfos.size());
    }

    /**
     * 修复照片分配逻辑 - 确保照片正确绑定
     */
    private void assignPhotosToTires(List<TireBatchDto.TireInfo> tireInfos, MultipartFile[] allPhotos) {
        log.info("=== 开始修复照片分配 ===");
        log.info("轮胎数量: {}, 总照片数量: {}", tireInfos.size(), allPhotos != null ? allPhotos.length : 0);

        if (allPhotos == null || allPhotos.length == 0) {
            log.info("没有照片需要分配");
            // 确保所有轮胎的照片字段设置为空数组而不是null
            for (TireBatchDto.TireInfo tireInfo : tireInfos) {
                tireInfo.setPhotos(new MultipartFile[0]);
            }
            return;
        }

        int photoIndex = 0;
        int totalAssigned = 0;

        for (TireBatchDto.TireInfo tireInfo : tireInfos) {
            List<MultipartFile> tirePhotosList = new ArrayList<>();
            int photosPerTire = 3;

            for (int i = 0; i < photosPerTire && photoIndex < allPhotos.length; i++) {
                MultipartFile photo = allPhotos[photoIndex];
                if (isValidPhoto(photo)) {
                    tirePhotosList.add(photo);
                    log.info("✅ 分配照片 [{}] {} (大小: {} bytes) 给轮胎 {}",
                            photoIndex, photo.getOriginalFilename(),
                            photo.getSize(), tireInfo.getTireNumber());
                    photoIndex++;
                    totalAssigned++;
                } else {
                    log.warn("❌ 跳过无效照片: index={}, 文件名={}, 大小={}",
                            photoIndex,
                            photo != null ? photo.getOriginalFilename() : "null",
                            photo != null ? photo.getSize() : 0);
                    photoIndex++;
                }
            }

            // 关键修复：确保即使没有照片也设置空数组
            MultipartFile[] tirePhotosArray = tirePhotosList.toArray(new MultipartFile[0]);
            tireInfo.setPhotos(tirePhotosArray);

            if (tirePhotosArray.length > 0) {
                log.info("🎯 轮胎 {} 成功分配到 {} 张照片", tireInfo.getTireNumber(), tirePhotosArray.length);
            } else {
                log.info("ℹ️  轮胎 {} 没有分配到照片", tireInfo.getTireNumber());
            }
        }

        log.info("=== 照片分配完成 ===");
        log.info("总共分配了 {} 张照片给 {} 个轮胎", totalAssigned, tireInfos.size());
        log.info("剩余未分配照片: {}", allPhotos.length - photoIndex);
    }

    /**
     * 检查照片是否有效
     */
    private boolean isValidPhoto(MultipartFile photo) {
        return photo != null &&
                !photo.isEmpty() &&
                photo.getSize() > 0 &&
                photo.getOriginalFilename() != null &&
                !photo.getOriginalFilename().trim().isEmpty();
    }
    /**
     * 获取轮胎统计数据
     */
    @GetMapping("/statistics/data")
    public ResponseEntity<Map<String, Object>> getTireStatistics(
            @RequestParam(required = false) String transportCompany,
            @RequestParam(required = false) String vehiclePlateNumber,
            @RequestParam(required = false) String trailerPlateNumber,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate,
            HttpServletRequest request) {

        try {
            User currentUser = getCurrentUser(request);

            if (transportCompany != null && !hasAccessToCompany(currentUser, transportCompany)) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("error", "无权访问该运输公司的数据");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(errorResponse);
            }

            // 对于COMPANY和DRIVER角色，强制使用用户注册时的公司
            if (currentUser.getRole() == User.UserRole.COMPANY || currentUser.getRole() == User.UserRole.DRIVER) {
                transportCompany = currentUser.getTransportCompany();
            }

            // 对于DRIVER角色，强制使用用户注册时的车辆
            if (currentUser.getRole() == User.UserRole.DRIVER) {
                vehiclePlateNumber = currentUser.getVehiclePlateNumber();
            }

            Map<String, Object> statistics = tireService.getTireStatistics(
                    transportCompany, vehiclePlateNumber, trailerPlateNumber, startDate, endDate);
            return ResponseEntity.ok(statistics);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "获取统计数据失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    /**
     * 按品牌型号统计
     */
    @GetMapping("/statistics/by-brand")
    public ResponseEntity<List<Map<String, Object>>> getStatisticsByBrand(
            @RequestParam(required = false) String transportCompany,
            @RequestParam(required = false) String vehiclePlateNumber,
            @RequestParam(required = false) String trailerPlateNumber,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate,
            HttpServletRequest request) {

        try {
            User currentUser = getCurrentUser(request);

            if (transportCompany != null && !hasAccessToCompany(currentUser, transportCompany)) {
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(null);
            }

            // 对于COMPANY和DRIVER角色，强制使用用户注册时的公司
            if (currentUser.getRole() == User.UserRole.COMPANY || currentUser.getRole() == User.UserRole.DRIVER) {
                transportCompany = currentUser.getTransportCompany();
            }

            // 对于DRIVER角色，强制使用用户注册时的车辆
            if (currentUser.getRole() == User.UserRole.DRIVER) {
                vehiclePlateNumber = currentUser.getVehiclePlateNumber();
            }

            List<Map<String, Object>> brandStats = tireService.getStatisticsByBrand(
                    transportCompany, vehiclePlateNumber, trailerPlateNumber, startDate, endDate);
            return ResponseEntity.ok(brandStats);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    /**
     * 查询使用记录
     */
    @PostMapping("/usage/query")
    public ResponseEntity<Map<String, Object>> getUsageRecord(@RequestParam String tireNumber, HttpServletRequest request) {
        User currentUser = getCurrentUser(request);
        TireService.TireUsageStats stats = tireService.getTireUsageStats(tireNumber);

        if (stats.getTire() != null && !hasAccessToTire(currentUser, stats.getTire())) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "无权查看此轮胎的使用记录");
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body(errorResponse);
        }

        Map<String, Object> result = new HashMap<>();
        result.put("stats", stats);

        // 根据用户角色返回相应的运输公司列表
        List<String> companies;
        if (currentUser.getRole() == User.UserRole.ADMIN) {
            companies = tireService.getAllTransportCompanies();
        } else if (currentUser.getRole() == User.UserRole.COMPANY || currentUser.getRole() == User.UserRole.DRIVER) {
            if (currentUser.getTransportCompany() != null) {
                companies = Collections.singletonList(currentUser.getTransportCompany());
            } else {
                companies = new ArrayList<>();
            }
        } else {
            companies = new ArrayList<>();
        }
        result.put("transportCompanies", companies);

        return ResponseEntity.ok(result);
    }

    /**
     * 轮胎号自动补全
     */
    @GetMapping("/autocomplete/tire-numbers")
    public List<String> autocompleteTireNumbers(@RequestParam String term, HttpServletRequest request) {
        User currentUser = getCurrentUser(request);
        return tireService.findTireNumbersByPattern(term, currentUser);
    }

    /**
     * 车牌号自动补全
     */
    @GetMapping("/autocomplete/plate-numbers")
    public List<String> autocompletePlateNumbers(@RequestParam String term, HttpServletRequest request) {
        User currentUser = getCurrentUser(request);
        try {
            List<String> results = tireService.findPlateNumbersByPattern(term, currentUser);
            return results;
        } catch (Exception e) {
            log.error("车牌号自动补全查询失败: " + e.getMessage());
            return new ArrayList<>();
        }
    }

    /**
     * 添加修补记录
     */
    @PostMapping("/{id}/repair")
    public ResponseEntity<Map<String, Object>> addRepairRecord(@PathVariable("id") Long id,
                                                               @RequestParam String repairRecord,
                                                               @RequestParam Integer repairMileage,
                                                               @RequestParam BigDecimal repairCost,
                                                               @RequestParam(value = "repairPhotos", required = false) MultipartFile[] repairPhotos,
                                                               HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();
        try {
            User currentUser = getCurrentUser(request);
            Tire tire = tireService.findById(id)
                    .orElseThrow(() -> new RuntimeException("轮胎不存在，ID: " + id));

            if (!hasAccessToTire(currentUser, tire)) {
                response.put("success", false);
                response.put("message", "无权为此轮胎添加修补记录");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(response);
            }

            tireService.addRepairRecord(tire, repairRecord, repairMileage, repairCost);

            if (repairPhotos != null && repairPhotos.length > 0) {
                tirePhotoService.saveRepairPhotos(id, repairPhotos, repairRecord);
            }

            response.put("success", true);
            response.put("message", "修补记录添加成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "添加修补记录失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 专门为Android设计的修补记录接口
     */
    @PostMapping("/android/{id}/repair")
    public ResponseEntity<Map<String, Object>> addRepairRecordForAndroid(
            @PathVariable("id") Long id,
            @RequestParam("repairRecord") String repairRecord,
            @RequestParam("repairMileage") Integer repairMileage,
            @RequestParam("repairCost") String repairCostStr,
            @RequestParam(value = "repairPhotos", required = false) MultipartFile[] repairPhotos,
            HttpServletRequest request) {

        Map<String, Object> response = new HashMap<>();
        User currentUser = getCurrentUser(request);

        try {
            BigDecimal repairCost = new BigDecimal(repairCostStr);
            Tire tire = tireService.findById(id)
                    .orElseThrow(() -> new RuntimeException("轮胎不存在，ID: " + id));

            if (!hasAccessToTire(currentUser, tire)) {
                response.put("success", false);
                response.put("message", "无权为此轮胎添加修补记录");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(response);
            }

            tireService.addRepairRecord(tire, repairRecord, repairMileage, repairCost);

            if (repairPhotos != null && repairPhotos.length > 0) {
                tirePhotoService.saveRepairPhotos(id, repairPhotos, repairRecord);
            }

            response.put("success", true);
            response.put("message", "修补记录添加成功");
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("添加修补记录失败", e);
            response.put("success", false);
            response.put("message", "添加修补记录失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 获取轮胎详情（JSON API - 用于Android客户端）
     */
    @GetMapping("/android/{id}")
    public ResponseEntity<ApiResponse<Tire>> getTireDetailApi(@PathVariable("id") Long id, HttpServletRequest request) {
        try {
            User currentUser = getCurrentUser(request);
            Optional<Tire> tireOptional = tireService.getTireById(id);
            if (tireOptional.isPresent()) {
                Tire tire = tireOptional.get();

                if (!hasAccessToTire(currentUser, tire)) {
                    ApiResponse<Tire> response = new ApiResponse<>();
                    response.setSuccess(false);
                    response.setMessage("无权查看此轮胎详情");
                    return ResponseEntity.status(HttpStatus.FORBIDDEN).body(response);
                }

                ApiResponse<Tire> response = new ApiResponse<>();
                response.setSuccess(true);
                response.setData(tire);
                response.setMessage("获取轮胎详情成功");

                return ResponseEntity.ok(response);
            } else {
                ApiResponse<Tire> response = new ApiResponse<>();
                response.setSuccess(false);
                response.setMessage("轮胎不存在");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }
        } catch (Exception e) {
            log.error("获取轮胎详情失败", e);
            ApiResponse<Tire> response = new ApiResponse<>();
            response.setSuccess(false);
            response.setMessage("获取轮胎详情失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 专门为Android设计的调胎记录接口（返回JSON）
     */
    @PostMapping("/android/{id}/swap")
    public ResponseEntity<ApiResponse<Void>> addSwapRecordForAndroid(
            @PathVariable("id") Long id,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate swapDate,
            @RequestParam Integer swapMileage,
            @RequestParam String swapCost,
            @RequestParam(required = false) String fromVehiclePlateNumber,
            @RequestParam(required = false) String fromTrailerPlateNumber,
            @RequestParam(required = false) Integer fromAxleNumber,
            @RequestParam(required = false) String fromTirePosition,
            @RequestParam(required = false) String toVehiclePlateNumber,
            @RequestParam(required = false) String toTrailerPlateNumber,
            @RequestParam(required = false) Integer toAxleNumber,
            @RequestParam(required = false) String toTirePosition,
            @RequestParam(required = false) String swapNote,
            @RequestParam String operationType,
            @RequestParam(required = false) Boolean confirmScrap,
            @RequestParam(value = "swapPhotos", required = false) MultipartFile[] swapPhotos,
            HttpServletRequest request) {

        try {
            User currentUser = getCurrentUser(request);
            Tire tire = tireService.getTireById(id).orElse(null);
            if (tire == null) {
                ApiResponse<Void> response = new ApiResponse<>();
                response.setSuccess(false);
                response.setMessage("轮胎不存在");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }

            if (!hasAccessToTire(currentUser, tire)) {
                ApiResponse<Void> response = new ApiResponse<>();
                response.setSuccess(false);
                response.setMessage("无权为此轮胎添加调胎记录");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(response);
            }

            BigDecimal cost = new BigDecimal(swapCost);
            Tire updatedTire = null;

            if ("scrap".equals(operationType)) {
                if (!Boolean.TRUE.equals(confirmScrap)) {
                    ApiResponse<Void> response = new ApiResponse<>();
                    response.setSuccess(false);
                    response.setMessage("请确认报废操作");
                    return ResponseEntity.badRequest().body(response);
                }

                updatedTire = tireService.swapAndScrapTire(
                        tire.getTireNumber(), swapDate, swapMileage, cost,
                        fromVehiclePlateNumber, fromTrailerPlateNumber, fromAxleNumber,
                        fromTirePosition, swapNote
                );

                if (updatedTire == null) {
                    ApiResponse<Void> response = new ApiResponse<>();
                    response.setSuccess(false);
                    response.setMessage("调胎报废失败");
                    return ResponseEntity.badRequest().body(response);
                }

            } else {
                updatedTire = tireService.addSwapRecord(
                        tire.getTireNumber(), swapDate, swapMileage, cost,
                        fromVehiclePlateNumber, fromTrailerPlateNumber, fromAxleNumber, fromTirePosition,
                        toVehiclePlateNumber, toTrailerPlateNumber, toAxleNumber, toTirePosition, swapNote
                );

                if (updatedTire == null) {
                    ApiResponse<Void> response = new ApiResponse<>();
                    response.setSuccess(false);
                    response.setMessage("正常调胎失败");
                    return ResponseEntity.badRequest().body(response);
                }
            }

            if (swapPhotos != null && swapPhotos.length > 0) {
                try {
                    String photoDescription = buildPhotoDescription(operationType, swapNote,
                            fromVehiclePlateNumber, fromAxleNumber, fromTirePosition,
                            toVehiclePlateNumber, toAxleNumber, toTirePosition);

                    tirePhotoService.saveSwapPhotos(id, swapPhotos, photoDescription, operationType);
                } catch (Exception e) {
                    log.error("保存调胎照片失败: " + e.getMessage());
                }
            }

            ApiResponse<Void> response = new ApiResponse<>();
            response.setSuccess(true);
            response.setMessage("调胎记录添加成功");
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("调胎操作异常: " + e.getMessage());
            ApiResponse<Void> response = new ApiResponse<>();
            response.setSuccess(false);
            response.setMessage("调胎操作失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 专门为Android设计的修改轮胎信息接口（返回JSON）
     */
    @PostMapping("/android/update")
    public ResponseEntity<ApiResponse<Void>> updateTireForAndroid(@RequestBody Map<String, Object> updateData, HttpServletRequest request) {
        try {
            User currentUser = getCurrentUser(request);
            log.info("Android修改轮胎请求数据: {}", updateData);

            if (updateData.get("id") == null) {
                ApiResponse<Void> response = new ApiResponse<>();
                response.setSuccess(false);
                response.setMessage("轮胎ID不能为空");
                return ResponseEntity.badRequest().body(response);
            }

            Long id = Long.valueOf(updateData.get("id").toString());
            Tire existingTire = tireService.findById(id)
                    .orElseThrow(() -> new RuntimeException("轮胎不存在"));

            if (!hasAccessToTire(currentUser, existingTire)) {
                ApiResponse<Void> response = new ApiResponse<>();
                response.setSuccess(false);
                response.setMessage("无权修改此轮胎信息");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(response);
            }

            String tireNumber = (String) updateData.get("tireNumber");

            if (tireNumber == null || tireNumber.trim().isEmpty()) {
                ApiResponse<Void> response = new ApiResponse<>();
                response.setSuccess(false);
                response.setMessage("轮胎号不能为空");
                return ResponseEntity.badRequest().body(response);
            }

            Optional<Tire> duplicateTire = tireService.findByTireNumber(tireNumber.trim());
            if (duplicateTire.isPresent() && !duplicateTire.get().getId().equals(id)) {
                ApiResponse<Void> response = new ApiResponse<>();
                response.setSuccess(false);
                response.setMessage("轮胎号已存在");
                return ResponseEntity.badRequest().body(response);
            }

            Tire tire = new Tire();
            tire.setId(id);
            tire.setTireNumber(tireNumber.trim());
            tire.setTireBrand((String) updateData.get("tireBrand"));
            tire.setTireModel((String) updateData.get("tireModel"));
            tire.setVehiclePlateNumber((String) updateData.get("vehiclePlateNumber"));
            tire.setTrailerPlateNumber((String) updateData.get("trailerPlateNumber"));

            if (currentUser.getRole() == User.UserRole.ADMIN) {
                tire.setTransportCompany((String) updateData.get("transportCompany"));
            } else {
                tire.setTransportCompany(existingTire.getTransportCompany());
            }

            if (updateData.get("tirePrice") != null) {
                try {
                    BigDecimal tirePrice = new BigDecimal(updateData.get("tirePrice").toString());
                    tire.setTirePrice(tirePrice);
                } catch (NumberFormatException e) {
                    log.warn("轮胎价格格式错误: {}", updateData.get("tirePrice"));
                }
            }

            if (updateData.get("installCost") != null) {
                try {
                    BigDecimal installCost = new BigDecimal(updateData.get("installCost").toString());
                    tire.setInstallCost(installCost);
                } catch (NumberFormatException e) {
                    log.warn("安装费用格式错误: {}", updateData.get("installCost"));
                }
            }

            if (updateData.get("installMileage") != null) {
                try {
                    Integer installMileage = Integer.valueOf(updateData.get("installMileage").toString());
                    tire.setInstallMileage(installMileage);
                } catch (NumberFormatException e) {
                    log.warn("安装里程格式错误: {}", updateData.get("installMileage"));
                }
            }

            if (updateData.get("installDate") != null) {
                try {
                    String installDateStr = (String) updateData.get("installDate");
                    if (!installDateStr.isEmpty()) {
                        LocalDate installDate = LocalDate.parse(installDateStr);
                        tire.setInstallDate(installDate);
                    }
                } catch (Exception e) {
                    log.warn("安装日期格式错误: {}", updateData.get("installDate"));
                }
            }

            tireService.updateTireBasicInfo(tire);

            ApiResponse<Void> response = new ApiResponse<>();
            response.setSuccess(true);
            response.setMessage("轮胎信息修改成功");
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("修改轮胎信息失败", e);
            ApiResponse<Void> response = new ApiResponse<>();
            response.setSuccess(false);
            response.setMessage("修改轮胎信息失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 通用的修改轮胎信息接口（支持PUT请求）
     */
    @PutMapping("/update")
    public ResponseEntity<Map<String, Object>> updateTire(@RequestBody Map<String, Object> updateData, HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();
        try {
            User currentUser = getCurrentUser(request);
            log.info("修改轮胎请求数据: {}", updateData);

            if (updateData.get("id") == null) {
                response.put("success", false);
                response.put("message", "轮胎ID不能为空");
                return ResponseEntity.badRequest().body(response);
            }

            Long id = Long.valueOf(updateData.get("id").toString());
            Tire existingTire = tireService.findById(id)
                    .orElseThrow(() -> new RuntimeException("轮胎不存在"));

            if (!hasAccessToTire(currentUser, existingTire)) {
                response.put("success", false);
                response.put("message", "无权修改此轮胎信息");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(response);
            }

            String tireNumber = (String) updateData.get("tireNumber");

            if (tireNumber == null || tireNumber.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "轮胎号不能为空");
                return ResponseEntity.badRequest().body(response);
            }

            Optional<Tire> duplicateTire = tireService.findByTireNumber(tireNumber.trim());
            if (duplicateTire.isPresent() && !duplicateTire.get().getId().equals(id)) {
                response.put("success", false);
                response.put("message", "轮胎号已存在");
                return ResponseEntity.badRequest().body(response);
            }

            Tire tire = new Tire();
            tire.setId(id);
            tire.setTireNumber(tireNumber.trim());
            tire.setTireBrand((String) updateData.get("tireBrand"));
            tire.setTireModel((String) updateData.get("tireModel"));
            tire.setVehiclePlateNumber((String) updateData.get("vehiclePlateNumber"));
            tire.setTrailerPlateNumber((String) updateData.get("trailerPlateNumber"));

            if (currentUser.getRole() == User.UserRole.ADMIN) {
                tire.setTransportCompany((String) updateData.get("transportCompany"));
            } else {
                tire.setTransportCompany(existingTire.getTransportCompany());
            }

            if (updateData.get("tirePrice") != null) {
                try {
                    BigDecimal tirePrice = new BigDecimal(updateData.get("tirePrice").toString());
                    tire.setTirePrice(tirePrice);
                } catch (NumberFormatException e) {
                    log.warn("轮胎价格格式错误: {}", updateData.get("tirePrice"));
                }
            }

            if (updateData.get("installCost") != null) {
                try {
                    BigDecimal installCost = new BigDecimal(updateData.get("installCost").toString());
                    tire.setInstallCost(installCost);
                } catch (NumberFormatException e) {
                    log.warn("安装费用格式错误: {}", updateData.get("installCost"));
                }
            }

            if (updateData.get("installMileage") != null) {
                try {
                    Integer installMileage = Integer.valueOf(updateData.get("installMileage").toString());
                    tire.setInstallMileage(installMileage);
                } catch (NumberFormatException e) {
                    log.warn("安装里程格式错误: {}", updateData.get("installMileage"));
                }
            }

            if (updateData.get("installDate") != null) {
                try {
                    String installDateStr = (String) updateData.get("installDate");
                    if (!installDateStr.isEmpty()) {
                        LocalDate installDate = LocalDate.parse(installDateStr);
                        tire.setInstallDate(installDate);
                    }
                } catch (Exception e) {
                    log.warn("安装日期格式错误: {}", updateData.get("installDate"));
                }
            }

            tireService.updateTireBasicInfo(tire);

            response.put("success", true);
            response.put("message", "轮胎信息修改成功");
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("修改轮胎信息失败", e);
            response.put("success", false);
            response.put("message", "修改轮胎信息失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 报废轮胎
     */
    @PostMapping("/{id}/scrap")
    public ResponseEntity<Map<String, Object>> scrapTire(@PathVariable Long id, @RequestParam Integer scrapMileage, HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();
        User currentUser = getCurrentUser(request);
        Tire tire = tireService.getTireById(id).orElse(null);
        if (tire != null && hasAccessToTire(currentUser, tire)) {
            tireService.scrapTire(tire.getTireNumber(), scrapMileage);
            response.put("success", true);
            response.put("message", "轮胎报废成功");
            return ResponseEntity.ok(response);
        } else {
            response.put("success", false);
            response.put("message", "轮胎不存在或无权操作");
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 根据运输公司查询轮胎
     */
    @GetMapping("/company/{company}")
    public List<Tire> getTiresByCompany(@PathVariable String company, HttpServletRequest request) {
        User currentUser = getCurrentUser(request);

        if (!hasAccessToCompany(currentUser, company)) {
            return new ArrayList<>();
        }

        return tireService.getTiresByTransportCompany(company);
    }

    /**
     * 根据位置查询轮胎
     */
    @GetMapping("/position/{position}")
    public List<Tire> getTiresByPosition(@PathVariable String position, HttpServletRequest request) {
        User currentUser = getCurrentUser(request);
        List<Tire> tires;

        switch (currentUser.getRole()) {
            case DRIVER:
                tires = tireService.getTiresByPositionAndVehicle(position, currentUser.getVehiclePlateNumber());
                break;
            case COMPANY:
                tires = tireService.getTiresByPositionAndCompany(position, currentUser.getTransportCompany());
                break;
            case ADMIN:
                tires = tireService.getTiresByPosition(position);
                break;
            default:
                tires = new ArrayList<>();
        }

        return tires;
    }

    /**
     * 添加调胎记录（支持正常调胎和调胎报废）
     */
    @PostMapping("/{id}/swap")
    public ResponseEntity<Map<String, Object>> addSwapRecord(@PathVariable Long id,
                                                             @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate swapDate,
                                                             @RequestParam Integer swapMileage,
                                                             @RequestParam String swapCost,
                                                             @RequestParam(required = false) String fromVehiclePlateNumber,
                                                             @RequestParam(required = false) String fromTrailerPlateNumber,
                                                             @RequestParam(required = false) Integer fromAxleNumber,
                                                             @RequestParam(required = false) String fromTirePosition,
                                                             @RequestParam(required = false) String toVehiclePlateNumber,
                                                             @RequestParam(required = false) String toTrailerPlateNumber,
                                                             @RequestParam(required = false) Integer toAxleNumber,
                                                             @RequestParam(required = false) String toTirePosition,
                                                             @RequestParam(required = false) String swapNote,
                                                             @RequestParam String operationType,
                                                             @RequestParam(required = false) Boolean confirmScrap,
                                                             @RequestParam(value = "swapPhotos", required = false) MultipartFile[] swapPhotos,
                                                             HttpServletRequest request) {

        Map<String, Object> response = new HashMap<>();
        User currentUser = getCurrentUser(request);
        Tire tire = tireService.getTireById(id).orElse(null);
        if (tire == null) {
            response.put("success", false);
            response.put("message", "轮胎不存在");
            return ResponseEntity.badRequest().body(response);
        }

        if (!hasAccessToTire(currentUser, tire)) {
            response.put("success", false);
            response.put("message", "无权操作此轮胎");
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body(response);
        }

        try {
            BigDecimal cost = new BigDecimal(swapCost);
            Tire updatedTire = null;

            if ("scrap".equals(operationType)) {
                if (!Boolean.TRUE.equals(confirmScrap)) {
                    response.put("success", false);
                    response.put("message", "请确认报废操作");
                    return ResponseEntity.badRequest().body(response);
                }

                updatedTire = tireService.swapAndScrapTire(
                        tire.getTireNumber(), swapDate, swapMileage, cost,
                        fromVehiclePlateNumber, fromTrailerPlateNumber, fromAxleNumber,
                        fromTirePosition, swapNote
                );

                if (updatedTire == null) {
                    response.put("success", false);
                    response.put("message", "调胎报废失败");
                    return ResponseEntity.badRequest().body(response);
                }

            } else {
                updatedTire = tireService.addSwapRecord(
                        tire.getTireNumber(), swapDate, swapMileage, cost,
                        fromVehiclePlateNumber, fromTrailerPlateNumber, fromAxleNumber, fromTirePosition,
                        toVehiclePlateNumber, toTrailerPlateNumber, toAxleNumber, toTirePosition, swapNote
                );

                if (updatedTire == null) {
                    response.put("success", false);
                    response.put("message", "正常调胎失败");
                    return ResponseEntity.badRequest().body(response);
                }
            }

            if (swapPhotos != null && swapPhotos.length > 0) {
                try {
                    String photoDescription = buildPhotoDescription(operationType, swapNote,
                            fromVehiclePlateNumber, fromAxleNumber, fromTirePosition,
                            toVehiclePlateNumber, toAxleNumber, toTirePosition);

                    tirePhotoService.saveSwapPhotos(id, swapPhotos, photoDescription, operationType);
                } catch (Exception e) {
                    log.error("保存调胎照片失败: " + e.getMessage());
                }
            }

            response.put("success", true);
            response.put("message", "调胎记录添加成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("调胎操作异常: " + e.getMessage());
            response.put("success", false);
            response.put("message", "调胎操作失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 获取拖车可视化数据
     */
    @GetMapping("/visualization/trailer/{trailerPlateNumber}")
    public ResponseEntity<TireVisualizationDTO> getVisualization(
            @PathVariable String trailerPlateNumber,
            HttpServletRequest request) {
        try {
            User currentUser = getCurrentUser(request);

            // 检查权限：用户只能查看自己有权限访问的拖车
            List<Tire> trailerTires = tireService.getTiresByTrailerPlateNumber(trailerPlateNumber);
            if (!trailerTires.isEmpty() && !hasAccessToTire(currentUser, trailerTires.get(0))) {
                return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
            }

            TireVisualizationDTO visualization = tireService.getTrailerVisualization(trailerPlateNumber);
            return ResponseEntity.ok(visualization);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 搜索轮胎
     */
    @GetMapping("/search")
    public Map<String, Object> searchTires(
            @RequestParam(required = false) String tireNumber,
            @RequestParam(required = false) String plateNumber,
            @RequestParam(required = false) String company,
            @RequestParam(required = false) String status,
            HttpServletRequest request) {

        User currentUser = getCurrentUser(request);
        Map<String, Object> result = new HashMap<>();

        try {
            log.info("搜索轮胎 - 用户角色: {}, 运输公司: {}, 车牌号: {}",
                    currentUser.getRole(),
                    currentUser.getTransportCompany(),
                    currentUser.getVehiclePlateNumber());

            // 对于司机和公司角色，强制使用用户注册时的运输公司
            if (currentUser.getRole() == User.UserRole.DRIVER || currentUser.getRole() == User.UserRole.COMPANY) {
                company = currentUser.getTransportCompany();
                log.info("强制设置运输公司为: {}", company);
            }

            // 对于司机角色，强制使用用户注册时的车牌号
            if (currentUser.getRole() == User.UserRole.DRIVER) {
                plateNumber = currentUser.getVehiclePlateNumber();
                log.info("强制设置车牌号为: {}", plateNumber);
            }

            // 权限检查 - 只有当用户尝试访问特定公司时才检查
            if (company != null && !hasAccessToCompany(currentUser, company)) {
                log.warn("权限拒绝 - 用户: {} 尝试访问公司: {}", currentUser.getUsername(), company);
                result.put("error", "无权访问该运输公司的数据");
                result.put("tires", new ArrayList<>());
                result.put("statistics", createEmptyStatistics());
                return result;
            }

            List<Tire> filteredTires = tireService.searchTires(tireNumber, plateNumber, company, status, currentUser);
            log.info("搜索到 {} 条轮胎记录", filteredTires.size());

            // 构建统计信息
            Map<String, Object> statistics = new HashMap<>();
            statistics.put("totalTires", filteredTires.size());
            statistics.put("activeTires", filteredTires.stream().filter(t -> t.getScrapDate() == null).count());
            statistics.put("scrappedTires", filteredTires.stream().filter(t -> t.getScrapDate() != null).count());
            statistics.put("repairedTires", filteredTires.stream().filter(t ->
                    t.getRepairRecords() != null && !t.getRepairRecords().isEmpty()).count());

            result.put("tires", filteredTires);
            result.put("statistics", statistics);

            return result;
        } catch (Exception e) {
            log.error("搜索轮胎时发生错误", e);
            result.put("error", "搜索轮胎时发生错误: " + e.getMessage());
            result.put("tires", new ArrayList<>());
            result.put("statistics", createEmptyStatistics());
            return result;
        }
    }

    // 辅助方法：创建空的统计信息
    private Map<String, Object> createEmptyStatistics() {
        Map<String, Object> statistics = new HashMap<>();
        statistics.put("totalTires", 0);
        statistics.put("activeTires", 0);
        statistics.put("scrappedTires", 0);
        statistics.put("repairedTires", 0);
        return statistics;
    }

    // 构建照片描述信息
    private String buildPhotoDescription(String operationType, String swapNote,
                                         String fromVehiclePlate, Integer fromAxle, String fromPosition,
                                         String toVehiclePlate, Integer toAxle, String toPosition) {
        StringBuilder description = new StringBuilder();

        if ("scrap".equals(operationType)) {
            description.append("调胎报废记录");
        } else {
            description.append("正常调胎记录");
        }

        if (fromVehiclePlate != null || fromAxle != null || fromPosition != null) {
            description.append(" - 从: ");
            if (fromVehiclePlate != null) description.append(fromVehiclePlate).append(" ");
            if (fromAxle != null) description.append(fromAxle).append("轴");
            if (fromPosition != null) description.append(fromPosition);
        }

        if ("swap".equals(operationType) && (toVehiclePlate != null || toAxle != null || toPosition != null)) {
            description.append(" 到: ");
            if (toVehiclePlate != null) description.append(toVehiclePlate).append(" ");
            if (toAxle != null) description.append(toAxle).append("轴");
            if (toPosition != null) description.append(toPosition);
        }

        if (swapNote != null && !swapNote.trim().isEmpty()) {
            description.append(" - ").append(swapNote);
        }

        return description.toString();
    }
}